﻿using Common.Device.DeviceDb;
using Common.Device.Enums;
using Common.Device.Interfaces;
using Common.Device.Models;
using Common.Device.ViewModels;
using HandyControl.Controls;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using static MaterialDesignThemes.Wpf.Theme;

namespace Common.Device.Views.Dialogs
{
    /// <summary>
    /// DeviceEditView.xaml 的交互逻辑
    /// </summary>
    public partial class OrderEditView : UserControl
    {        
        static HandyControl.Controls.PopupWindow window;
        private OrderEditView()
        {
            InitializeComponent(); InitTimer();
        }
        /// <summary>
        /// 插入测试指令
        /// </summary>
        /// <param name="order">测试指令</param>
        public void InsertOrder(Order order)
        {
            try
            {
                var viewModel = this.DataContext as ViewModels.OrderEditViewModel;
                DeviceOrder deviceOrder = new DeviceOrder();
                if (DeviceList.SelectedItem != null)
                {
                    //有指令选中时提示是否进行修改或者新增指令
                    //提示 是，否，取消
                    var result = View.Controls.Dialogs.TipView.Show("发现有测试指令被选中,是否对所选指令进行修改？", new Dictionary<string, Brush> { { "修改", View.Base.Colors.PrimaryColor }, { "新增", View.Base.Colors.SuccessColor }, { "取消", View.Base.Colors.DangerColor } });
                    //取消
                    if (result == "取消")
                    {
                        return;
                    }
                    //是，进行更改
                    if (result == "修改")
                    {
                        deviceOrder = (DeviceOrder)DeviceList.SelectedItem;
                        deviceOrder.Device = viewModel.Device;
                        deviceOrder.Order = order;
                        viewModel.Orders = new System.Collections.ObjectModel.ObservableCollection<DeviceOrder>(viewModel.Orders);
                        return;
                    }
                }
                deviceOrder.index = viewModel.Orders.Count + 1;
                deviceOrder.Device = viewModel.Device;
                deviceOrder.no = Encoding.ASCII.GetString(new[] { (byte)(Encoding.ASCII.GetBytes("a")[0] + viewModel.Orders.Count) });
                deviceOrder.Order = order;
                viewModel.Orders.Add(deviceOrder);
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.ToString());
            }


        }
        /// <summary>
        /// 测试指令编辑界面
        /// </summary>
        /// <param name="order">测试指令</param>
        /// <returns></returns>
        public static TestOrder Show(TestOrder order = null)
        {
            TestOrder returnOrder = null; 
            try
            {
                OrderEditView view = new OrderEditView();
                ViewModels.OrderEditViewModel viewModel = new ViewModels.OrderEditViewModel();
                viewModel.DeviceNames.Add("函数模块");
                window = new HandyControl.Controls.PopupWindow
                {
                    ShowBorder = false,
                    ShowTitle = false,
                    Background = Brushes.Transparent,
                    PopupElement = view,//将当前用户控件加载到弹窗中
                    WindowStartupLocation = WindowStartupLocation.CenterScreen,
                    AllowsTransparency = true,
                    WindowStyle = WindowStyle.None,
                    MinWidth = 0,
                    MinHeight = 0
                };
                view.Loaded += (s, e) =>
                {
                    view.DataContext = viewModel;
                    if (order != null)
                    {
                        foreach (var item in order.orders)
                        {
                            viewModel.Orders.Add(item.Clone());
                        }
                        viewModel.NgStop = order.ngStop;
                        viewModel.Name = order.name;
                        viewModel.TestTimes = order.testTimes;
                    }
                };
                view.names.SelectionChanged += (s, e) =>
                {                   
                    string name = view.names.SelectedValue?.ToString();
                    if (!string.IsNullOrEmpty(name))
                    {
                        if (name != "函数模块")
                            viewModel.Device = DeviceService.useDevices[name];
                        else
                        {
                            //函数模块时没有可使用仪器
                            viewModel.Device = null;
                            view.names.SelectedIndex = viewModel.DeviceNames.Count - 1;
                        }
                        viewModel.SetDeviceView();
                    }
                };
                view.btnConfirm.Click += (s, e) =>
                {
                    //确认检查输入内容
                    if (string.IsNullOrEmpty(viewModel.Name))
                    {
                        HandyControl.Controls.MessageBox.Warning("请输入测试项名称!");
                        return;
                    }
                    if (viewModel.Orders.Count == 0)
                    {
                        HandyControl.Controls.MessageBox.Warning("测试内容为空!");
                        return;
                    }
                    //返回测试指令
                    returnOrder = new TestOrder();
                    returnOrder.orders = viewModel.Orders.ToList();
                    returnOrder.testTimes = viewModel.TestTimes;
                    returnOrder.name = viewModel.Name;
                    returnOrder.ngStop = viewModel.NgStop;
                    window?.Close();
                };
                window.ShowDialog();
            }
            catch (Exception ex)
            {
                HandyControl.Controls.MessageBox.Error(ex.ToString());
            }
            return returnOrder;
        }

        private void DeviceList_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            //双击解析指令到左侧编辑区
            var order = DeviceList.SelectedItem as Models.DeviceOrder;
            if (order == null)
            {
                return;
            }
            var viewModel = this.DataContext as ViewModels.OrderEditViewModel;
            viewModel.Device = order.Device;
            if (order.Device == null)
            {
                viewModel.DeviceName = "函数模块";
            }
            viewModel.SetDeviceView(order.Order);
        }
    

        private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                //触摸屏触发时跳过
                if (e.StylusDevice != null)
                {
                    e.Handled = true;
                }
                else
                {
                    window?.DragMove();
                }
            }
            catch (Exception)
            {

                //throw;
            }

        }
        //触摸屏触发
        private void Grid_PreviewTouchDown(object sender, TouchEventArgs e)
        {
            try
            {
                window?.DragMove();
            }
            catch (Exception)
            {

                // throw;
            }

        }
        private void closeClick(object sender, RoutedEventArgs e)
        {
            window?.Close();
        }
        #region 拖拽功能
        System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
        ListViewItem selectItem = null;
        int timeOut = 0;
        private void InitTimer()
        {
            try
            {
                //拖拽按下计时
                timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
                timer.Tick += new EventHandler(timer_Tick);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        void timer_Tick(object sender, EventArgs e)
        {
            try
            {
                //按下计时等于4次
                if (++timeOut == 4)
                {
                    // 获取被拖拽的项
                    draggedItem = DeviceList.ItemContainerGenerator.ItemFromContainer(selectItem);
                    // 开始拖拽操作
                    DragDrop.DoDragDrop(selectItem, draggedItem, DragDropEffects.Move);
                }
            }
            catch (Exception ex)
            {
                HandyControl.Controls.Growl.Error(ex.Message);
            }

        }
        private object draggedItem;
        private void ListView_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var listView = sender as System.Windows.Controls.ListView;
            // 获取鼠标点击的列表项
            var hitTestResult = VisualTreeHelper.HitTest(listView, e.GetPosition(listView));
            var listViewItem = FindVisualParent<ListViewItem>(hitTestResult.VisualHit);

            if (listViewItem != null)
            {
                //鼠标按下清空时间
                timeOut = 0;
                //选中项
                selectItem = listViewItem;
                //计时
                timer.Start();
            }
        }
        private void ListView_PreviewMouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            timeOut = 0;
            timer.Stop();
        }
        private void ListView_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent(typeof(DeviceOrder)))
            {
                e.Effects = DragDropEffects.None;
            }
        }
        private void ListView_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(typeof(DeviceOrder)))
            {
                var listView = sender as System.Windows.Controls.ListView;
                // 获取目标列表项
                var hitTestResult = VisualTreeHelper.HitTest(listView, e.GetPosition(listView));
                var targetListViewItem = FindVisualParent<ListViewItem>(hitTestResult.VisualHit);

                if (targetListViewItem != null)
                {
                    // 获取目标项的索引
                    int targetIndex = listView.ItemContainerGenerator.IndexFromContainer(targetListViewItem);

                    // 获取数据源
                    var items = (ObservableCollection<DeviceOrder>)listView.ItemsSource;

                    // 移除被拖拽的项
                    items.Remove((DeviceOrder)draggedItem);

                    // 在目标位置插入被拖拽的项
                    items.Insert(targetIndex, (DeviceOrder)draggedItem);
                    for (int i = 0; i < items.Count; i++)
                    {
                        items[i].index = i + 1;
                        items[i].no = Encoding.ASCII.GetString(new[] { (byte)(Encoding.ASCII.GetBytes("a")[0] + i) });
                    }
                    // 刷新列表视图
                    listView.Items.Refresh();
                }
            }
        }
        private static T FindVisualParent<T>(DependencyObject child) where T : DependencyObject
        {
            var parentObject = VisualTreeHelper.GetParent(child);
            if (parentObject == null) return null;
            if (parentObject is T parent)
            {
                return parent;
            }
            return FindVisualParent<T>(parentObject);
        }
        #endregion
    }
}
